<template>
  <div>
    <Button type="primary" @click="addRow" style="margin-bottom: 16px">
      添加行
    </Button>
    <Button type="primary" @click="saveChanges" style="margin-bottom: 16px; margin-left: 8px">
      保存
    </Button>
    <Table
      :columns="columnsWithOperation"
      :dataSource="localDataSource"
      :pagination="false"
      rowKey="id"
      bordered
    >
      <template #bodyCell="{ column, record }">
        <template v-if="editingCell.row === record.id && editingCell.col === column.dataIndex">
          <Input
            v-model:value="editCache[column.dataIndex]"
            @blur="saveEdit"
            @pressEnter="saveEdit"
          />
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <Button type="link" @click="removeRow(record.id)">删除</Button>
        </template>
        <template v-else>
          <span @click="editCell(record.id, column.dataIndex)">
            {{ record[column.dataIndex] }}
          </span>
        </template>
      </template>
    </Table>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { Table, Button, Input } from 'ant-design-vue';
import { v4 as uuidv4 } from 'uuid'; // 用于生成唯一ID

// Props
const props = defineProps({
  columns: {
    type: Array,
    required: true,
  },
  dataSource: {
    type: Array,
    default: () => [],
  },
});

// 本地数据源和变更记录
const localDataSource = reactive([...props.dataSource]);
const changedRecords = ref([]);

// 当前正在编辑的单元格
const editingCell = reactive({ row: null, col: null });

// 编辑时的临时缓存
const editCache = reactive({});

// 为 `columns` 添加操作列
const columnsWithOperation = computed(() => [
  ...props.columns,
  {
    title: '操作',
    key: 'operation',
    dataIndex: 'operation',
    width: 120,
  },
]);

// 动态生成新增行的默认值
const generateRowData = () => {
  const newRow = { id: uuidv4() }; // 使用唯一ID
  props.columns.forEach((col) => {
    if (col.dataIndex) {
      newRow[col.dataIndex] = '';
    }
  });
  return newRow;
};

// 添加行
const addRow = () => {
  const newRow = generateRowData();
  localDataSource.push(newRow);
  // 通过 emit 通知父组件更新数据
  emit('update:dataSource', [...localDataSource]);
};

// 删除行
const removeRow = (id) => {
  const index = localDataSource.findIndex((item) => item.id === id);
  if (index !== -1) {
    localDataSource.splice(index, 1);
  }
  // 同时删除变更记录中的对应行
  const changeIndex = changedRecords.value.findIndex((item) => item.id === id);
  if (changeIndex !== -1) {
    changedRecords.value.splice(changeIndex, 1);
  }
  // 通过 emit 通知父组件更新数据
  emit('update:dataSource', [...localDataSource]);
};

// 单击进入编辑模式
const editCell = (rowId, colKey) => {
  const record = localDataSource.find((item) => item.id === rowId);
  if (record) {
    editingCell.row = rowId;
    editingCell.col = colKey;
    editCache[colKey] = record[colKey];
  }
};

// 保存编辑
const saveEdit = () => {
  const record = localDataSource.find((item) => item.id === editingCell.row);
  if (record) {
    const colKey = editingCell.col;

    // 如果值发生变化，记录到变更记录
    if (record[colKey] !== editCache[colKey]) {
      record[colKey] = editCache[colKey]; // 更新数据源

      // 检查是否已存在于变更记录中
      const existingIndex = changedRecords.value.findIndex((item) => item.id === record.id);
      if (existingIndex !== -1) {
        changedRecords.value[existingIndex] = { ...record };
      } else {
        changedRecords.value.push({ ...record });
      }
    }
  }

  // 清空编辑状态
  editingCell.row = null;
  editingCell.col = null;
};

// 点击保存按钮
const saveChanges = () => {
  console.log('变更记录:', changedRecords.value);
};
</script>

<style scoped>
/* 鼠标指针样式 */
span {
  cursor: pointer;
}
</style>
